package fun.tan90.device.source.http.plugin.config;

import cn.hutool.core.util.StrUtil;
import fun.tan90.device.event.model.DeviceSourceData;
import fun.tan90.device.source.core.SourceFactory;
import io.vertx.core.MultiMap;
import io.vertx.core.Vertx;
import lombok.extern.slf4j.Slf4j;
import org.noear.snack.ONode;
import org.noear.solon.annotation.Component;

import java.util.function.BiConsumer;

@Slf4j
@Component
public class VertxHttpServerFactory extends SourceFactory {

    @Override
    public Class<?> init(ONode connectNode, BiConsumer<String, Object> biConsumer) {
        Vertx vertx = Vertx.vertx();
        for (ONode node : connectNode.ary()) {
            String name = node.get("name").getString();
            ONode config = node.get("config");
            String host = config.get("host").getString();
            int port = config.get("port").getInt();
            String uri = config.get("uri").getString();
            String method = config.get("method").getString();
            vertx.deployVerticle(new VertxHttpServer(name, host, port, uri, method, 1024 * 1024 * 10, ctx -> {
                String body = ctx.body().asString();
                log.info("请求体 {}", body);
                MultiMap queryParams = ctx.queryParams();
                String deviceCode = StrUtil.isBlank(queryParams.get("deviceCode")) ? ctx.pathParam("deviceCode") : queryParams.get("deviceCode");
                afterPost(new DeviceSourceData(uri, deviceCode, body));
                ctx.response().end();
            }), res -> {
                if (res.succeeded()) {
                    log.info("【{}】 HTTP 服务器已运行 【http://{}:{}{}】 deploymentId【{}】", name, host, port, uri, res.result());
                    serverInitSuccess();
                } else {
                    log.error("【{}】 HTTP 服务启动失败: {}", name, res.cause().getMessage());
                    serverInitFailure(res.cause());
                }
            });
        }
        biConsumer.accept(Vertx.class.getName(), vertx);
        return Vertx.class;
    }
}
